package top.revery.api.util;


import org.dom4j.*;
import org.dom4j.io.SAXReader;
import top.revery.api.config.WxConfig;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.*;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/19 14:42
 */
public class PayCommonUtil {

    /**
     * 获取本机IP地址
     * @return IP
     */
    private static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    //随机字符串生成
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 微信支付签名算法sign
     */
    public static String getSign(Map<String, Object> map) throws Exception {
        StringBuffer sb = new StringBuffer();
        String[] keyArr =map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
        Arrays.sort(keyArr);//对array排序
        for (int i = 0, size = keyArr.length; i < size; ++i) {
            if ("sign".equals(keyArr[i])) {
                continue;
            }
            sb.append(keyArr[i] + "="+ map.get(keyArr[i]) + "&");
        }
        sb.append("key=" + WxConfig.APP_KEY);
        String sign = MdUtils.MD5Encode(sb.toString(),"UTF-8").toUpperCase();
        return sign;
    }


    //生成签名sign
    public static String createSign(String characterEncoding,Map<String,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + WxConfig.APP_KEY);
        System.out.println(sb.toString());
        String sign = MdUtils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }




    /**
     * 通过返回IO流获取支付地址
     * @param in
     * @return
     */
    public static String getElementValue(String in, String key){
        SAXReader reader = new SAXReader();
        Document document=null;
        try {
            document = reader.read(in);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.getRootElement();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            System.out.println(child.getName()+":"+child.getStringValue());
            if(key.equals(child.getName())){
                return child.getStringValue();
            }
        }
        return null;
    }
 /*   public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? 0xff000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }*/

    /**
     * 验证回调签名
     * @return
     */
    public static boolean isTenpaySign(Map<String, String> map) {
        String characterEncoding="utf-8";
        String charset = "utf-8";
        String signFromAPIResponse = map.get("sign");
        if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
            System.out.println("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
        //过滤空 设置 TreeMap
        SortedMap<String,String> packageParams = new TreeMap();

        for (String parameter : map.keySet()) {
            String parameterValue = map.get(parameter);
            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" +  WxConfig.APP_KEY);

        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        //算出签名
        String resultSign = "";
        String tobesign = sb.toString();

        if (null == charset || "".equals(charset)) {
            resultSign = MdUtils.MD5Encode(tobesign, characterEncoding).toUpperCase();
        }else{
            try{
                resultSign = MdUtils.MD5Encode(tobesign, characterEncoding).toUpperCase();
            }catch (Exception e) {
                resultSign = MdUtils.MD5Encode(tobesign, characterEncoding).toUpperCase();
            }
        }

        String tenpaySign = ((String)packageParams.get("sign")).toUpperCase();
        return tenpaySign.equals(resultSign);
    }

    //解析xml字符串
    public static String getCodeUrl(String in) throws DocumentException {
        Document document= DocumentHelper.parseText(in);//xmlStr为上图格式的字符串
        Node code_url=document.selectSingleNode("//code_url");
        //根据节点对象获取相应信息
        String code=code_url.getText();
       return  code;
    }
}
